//
//  VGCollectionViewPageProtocol.swift
//  vgbox
//
//  Created by 宋海胜 on 2019/12/6.
//  Copyright © 2019 Swift Xcode. All rights reserved.
//  列表页扩展-2.0

import UIKit
import MJRefresh

/// 分页逻辑协议
protocol SYCollectionViewPageProtocol {
    
//    var vg_pagerModel: PYQPagerModel? { get set }
    var vg_pagerModel: SGPagerModel<SGPagerTestModel>? { get set }
    
    var vg_dataCount: Int { get set }
    
    var vg_isLoading: Bool { get set }
    
    var vg_pageNo: Int { get set }

    func vg_collectionViewGetList()
    
    func vg_collectionViewGetEmptyPageTitleAndImgUrl() -> (String, String, CGFloat, CGFloat)
}

// 在扩展中实现的方法为可选方法
extension SYCollectionViewPageProtocol {
    
    func vg_collectionViewGetEmptyPageTitleAndImgUrl() -> (String, String, CGFloat, CGFloat) {
        return ("暂无", "enro_mana_list_empty", -30, 30)
    }
}

struct UICollectionViewKeys {
    static var emptyView: UIView = UIView()
    
    static var pageNumberString  = "pageNumberString"
//    static var pageNumberKey = {return Unmanaged<AnyObject>.passUnretained(UICollectionViewKeys.pageNumberString as AnyObject).toOpaque()}()
    
    static var pageProtocolString  = "pageProtocolString"
    ///获取String标识的内存地址作为runtime属性的Key
//    static var pageProtocolKey = {return Unmanaged<AnyObject>.passUnretained(UICollectionViewKeys.pageProtocolString as AnyObject).toOpaque()}()
}


extension UICollectionView {
    
    internal var vg_pageProtocol: SYCollectionViewPageProtocol {
        get{
            return objc_getAssociatedObject(self, &UICollectionViewKeys.pageProtocolString) as! SYCollectionViewPageProtocol
        }
        set{
            objc_setAssociatedObject(self, &UICollectionViewKeys.pageProtocolString, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            guard let _ = objc_getAssociatedObject(self, &UICollectionViewKeys.emptyView) as? UIView else {
                self.vg_setupRefreshHeaderView()
                self.vg_setupRefreshFooterView()
                self.vg_setupEmptyView()
                return
            }
        }
    }
    
    public var vg_emptyView: UIView {
        get{
            return objc_getAssociatedObject(self, &UICollectionViewKeys.emptyView) as! UIView
        }
        set{
            objc_setAssociatedObject(self, &UICollectionViewKeys.emptyView, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    
    
    // MARK: - ******************************************* 分页相关 *******************************************
    // 分页逻辑相关 - 头部view
    public func vg_setupRefreshHeaderView() {
        
        let loadTextHeight = self.vg_pageProtocol.vg_collectionViewGetEmptyPageTitleAndImgUrl().3
        let mjHeader = MJHeaderView(frame: CGRect(x: 0, y: 0, width: self.frame.width, height: 30), refreshText: Constant_Toast.loadingText, height: loadTextHeight)
        mjHeader.refreshingBlock = {[weak self] in
            if let weakSelf = self {
                if (weakSelf.vg_pageProtocol.vg_isLoading) {
                    return;
                } else {
                    weakSelf.vg_pageProtocol.vg_pageNo = 1
                    weakSelf.vg_pageProtocol.vg_collectionViewGetList()
                }
            }
        }
        self.mj_header = mjHeader
        self.mj_header?.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: 30) // 父类有问题 必须要加上，不然顶部会多一块
    }
    
    // 分页逻辑相关 - 尾部view
    public func vg_setupRefreshFooterView() {
        
        let mjFooter = MJRefreshAutoNormalFooter(frame: CGRect(x: 0, y: 0, width: self.frame.width, height: 30))
        mjFooter.refreshingBlock = {[weak self] in
            if let weakSelf = self {
                if (weakSelf.vg_pageProtocol.vg_isLoading) {
                    return;
                } else {
                    if let p = weakSelf.vg_pageProtocol.vg_pagerModel, let t = p.pages, t > 1 {
                        weakSelf.vg_pageProtocol.vg_pageNo += 1
                        weakSelf.vg_pageProtocol.vg_collectionViewGetList()
                    }
                }
            }
        }
        self.mj_footer = mjFooter
        self.mj_footer?.isHidden = true
    }
    
    // 分页逻辑相关 - 空页面
    public func vg_setupEmptyView() {
        vg_emptyView = UIView(frame: CGRect(x:0.0, y:0.0, width: SCREEN_WIDTH, height: self.frame.size.height))
        vg_emptyView.backgroundColor = .purple//Constant.bgViewColor
        let contentImg: UIImageView = UIImageView()
        let contentLb: UILabel = UILabel()
        var contentOffY: CGFloat = 0
        let titleAndImgUrl: (title: String, imgUrl: String, offY: CGFloat, headerHeight: CGFloat) = self.vg_pageProtocol.vg_collectionViewGetEmptyPageTitleAndImgUrl()
        contentLb.text = titleAndImgUrl.title
        contentImg.image = UIImage(named: titleAndImgUrl.imgUrl)
        contentOffY = titleAndImgUrl.offY
        
        contentLb.textAlignment = .center
        contentLb.textColor = Constant.color_104
        contentLb.font = UIFont.systemFont(ofSize: 15)
        
        vg_emptyView.addSubview(contentImg)
        vg_emptyView.addSubview(contentLb)
        self.addSubview(vg_emptyView)
        vg_emptyView.isHidden = true
        
        contentImg.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview().offset(contentOffY)
        }
        contentLb.snp.makeConstraints { (make) in
            make.top.equalTo(contentImg.snp.bottom).offset(5)
            make.centerX.equalToSuperview()
            make.height.equalTo(20)
        }
    }
    
    // 分页逻辑相关 - 结束刷新
    public func vg_endCollectionViewRefresh() {
        
        if nil == self.vg_pageProtocol.vg_pagerModel { // 无分页
            // 结束顶部刷新
            self.mj_header?.endRefreshing();
            // 数据已经到底
            self.mj_footer?.endRefreshingWithNoMoreData()
            self.mj_footer?.isHidden = true
            // 无任何数据 空页面
            self.vg_emptyView.isHidden = self.vg_pageProtocol.vg_dataCount != 0
        } else { // 有分页
            
            if self.vg_pageProtocol.vg_pagerModel?.pages == 0 {
                // 结束顶部刷新
                self.mj_header?.endRefreshing();
                // 无任何数据 空页面
                self.vg_emptyView.isHidden = false
            } else if (self.vg_pageProtocol.vg_pageNo == 1) {
                // 结束顶部刷新
                self.mj_header?.endRefreshing();
                self.mj_footer?.state = .idle
                self.vg_emptyView.isHidden = true
                if self.vg_pageProtocol.vg_pagerModel?.pages == 1 {
                    // 数据只有一页
                    self.mj_footer?.endRefreshingWithNoMoreData()
                    self.mj_footer?.isHidden = true
                } else if let p = self.vg_pageProtocol.vg_pagerModel?.pages, p > 1 {
                    self.mj_footer?.isHidden = false
                }
            } else {
                if self.vg_pageProtocol.vg_pagerModel?.current == self.vg_pageProtocol.vg_pagerModel?.pages {
                    // 数据已经到底
                    self.mj_footer?.endRefreshingWithNoMoreData()
                    self.mj_footer?.isHidden = true
                } else {
                    // 结束底部刷新
                    self.mj_footer?.endRefreshing();
                    self.mj_footer?.isHidden = false
                }
                self.vg_emptyView.isHidden = true
            }
        }
    }

}



